import Vue from "vue";
import Vuex from "vuex";
import defaultRouter from '../router/defaultRouter';
import allRouter from '../router/allRouter'
import { postMethod, getMethod } from "../utils/http";
import { getSession, setSession, remSession ,JSONStringify,JSONParse} from "../utils/common";
Vue.use(Vuex);
const store = new Vuex.Store({
  state: {
    routers: getSession('user-routers') ? getSession('user-routers') : defaultRouter,
    schoolId: getSession('user-schoolId'),
    userInfo: getSession('user-info') == 0 ? getSession('user-info') : JSON.parse(getSession('user-info')),
    allRouter: JSON.parse(getSession('user-allRouter'))||[],
  },
  mutations: {
    updatedallRouter(state, data) {
      state.allRouter = data;
    },
    updatedRouters(state, data) {
      state.routers = data;
    },
    updatedSchoolId(state, data) {
      state.schoolId = data;
    },
    updatedUserInfo(state, data) {
      state.userInfo = data;
    },
  },
  actions: {
    //获取匹配后的路由 并合并路由表里的 首页的路由
    async setRouter({ commit }, user) {
      remSession(['user-routers', 'user-schoolId', 'user-info','user-allRouter']);
      const getUser = await postMethod(`xyxy/wxapp/web/pub/login?account=${user.account}&password=${user.password}`, {});
      if (getUser.code == 1) {
        setSession('user-info', getUser.data == 0 ? getUser.data : JSON.stringify(getUser.data));
        commit('updatedUserInfo', getUser.data);
        let routers = defaultRouter;
        if (getUser.data != 0) {
          // getUser.data.route.split(",").forEach(i => {
          //   const routeItem = allRouter.find(t => {
          //     return i === t.path;
          //   });
          //   if (routeItem) routers[0].children.push(routeItem);
          // });
          setSession('user-schoolId', getUser.data.id);
          setSession('user-routers', getUser.data.route);
          commit('updatedSchoolId', getUser.data.id);
          commit('updatedRouters', getUser.data.route);
        }
        // else {
        //   routers[0].children = allRouter;
        // }
        // console.log(routers,routers.toString());
        setSession('user-allRouter',JSON.stringify(routers));
        // commit('updatedallRouter', routers);
      }
      return getUser;
    }
  },
  getters: {
    // updatedStateRouters(state) {
    //   return state.userRole
    // }
  }

})

export default store

//筛选所有路由中  包含匹配的规则的  存在返回true
function isExistence(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.indexOf(role) > -1);
  } else {
    return false
  }
}
//递归一下  把存在返回true 的 存到一个新数组里
function recursionRouter(allRouter = [], roles = [],) {
  var realRoutes = []
  allRouter.forEach((v, i) => {
    const tmp = { ...v };
    if (isExistence(roles, tmp)) {
      if (tmp.children) {
        tmp.children = recursionRouter(tmp.children, roles);
      }
      realRoutes.push(tmp);
    }
  })
  return realRoutes
}
